package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.mysql.User;
import com.tanhua.model.utils.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    /**
     * redis pre key
     */
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MQService mqService;

    @DubboReference
    private UserApi userApi;

    public void sendMsg(String phone) {
        User user = userApi.findByMobile(phone);
        if(user != null) {
            userFreezeService.checkUserStatus(1, user.getId());
        }
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        //2、调用template对象，发送手机短信
        //smsTemplate.sendSms(phone,code);
        String code = "111111";
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set(Constants.SMS_CODE + phone, code, 5, TimeUnit.MINUTES);
    }

    public Map loginVerification(String phone, String code) {
        checkVerificationCode(phone, code);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        //5、如果用户不存在，创建用户保存到数据库中
        Boolean isNew = false;
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
            mqService.sendLog(user.getId(),"0102","registe",null);
        }
        //6、通过JWT生成token(存入id和手机号码)
        HashMap<String, Object> tokenMap = new HashMap<>(2);
        tokenMap.put("id", user.getId());
        tokenMap.put("phone", user.getMobile());
        String token = JwtUtils.getToken(tokenMap);
        //
        String pullKey = Constants.PEACH_PULL_TIMES + user.getId();
        String pushKey = Constants.PEACH_PUSH_TIMES + user.getId();
        if (!redisTemplate.hasKey(pushKey)) {
            redisTemplate.opsForValue().set(pushKey, 10, 1, TimeUnit.DAYS);
            redisTemplate.opsForValue().set(pullKey, 10, 1, TimeUnit.DAYS);
        }
        //
        mqService.sendLog(user.getId(),"0101","login",null);
        //7、构造返回值
        Map<String, Object> restMap = new HashMap<>(2);
        restMap.put("token", token);
        restMap.put("isNew", isNew);
        return restMap;
    }

    /**
     * description: <通用>短信验证码效验 <br>
     * version: 1.0 <br>
     * date: 2021/11/14 18:24 <br>
     * author: SangWu <br>
     *
     * @param phone
     * @param code
     * @return void
     */
    public void checkVerificationCode(String phone, String code) {
        //1、从redis中获取下发的验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(codeInRedis) || !codeInRedis.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete(Constants.SMS_CODE + phone);
    }

    public Map<String, String> findHuanXin() {
        Long userId = UserHolder.getUserId();
        User user = userApi.findById(userId);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("username", user.getHxUser());
        map.put("password", user.getHxPassword());
        return map;
    }
}
